import 'dart:io';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/mypage/mypage_attendance_ecord_widget/text_limit_display_util.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import '../../app_main.dart';
import '../my_page_view_model.dart';
import 'detailed_bean/mypage_proposal_bean.dart';

class MyPageFeedBackDetailsWidget extends StatefulWidget {
  const MyPageFeedBackDetailsWidget({Key key}) : super(key: key);
  @override
  _MyPageFeedBackDetailsWidgetState createState() => _MyPageFeedBackDetailsWidgetState();

  static Future<dynamic> navigatorPush(
      BuildContext context
      ) {
    return RouterUtils.routeForFutureResult(
      context,
      MyPageFeedBackDetailsWidget(
      ),
    );
  }
}

class _MyPageFeedBackDetailsWidgetState extends BaseState<MyPageFeedBackDetailsWidget> {
  MyPageViewModel viewModel;
  List<RecordsImprovementListBean> improvementListData;
  // List<UploadMediaLibraryItemBean> _picVidDataList = List();
  @override
  void initState() {
    super.initState();
    viewModel = MyPageViewModel(this);
    viewModel?.recordsImprovementListValue?.addListener(() {
      setState(() {
        improvementListData = viewModel?.recordsImprovementListValue?.value;
      });
    });
    viewModel?.getSuggestionListData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _feedbackDetailsWidget(),
    );
  }

  Widget _feedbackDetailsWidget(){
    return Column(
      children: [
        _toTopBarWidget(),
        showSuggestionListWidget(),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(title: "意见反馈·${improvementListData?.length??0}", isShowBack: true);
  }

  Widget showSuggestionListWidget(){
    return Expanded(
      child: VgPlaceHolderStatusWidget(
        loadingStatus: improvementListData == null,
        errorStatus :  improvementListData == null,
        emptyStatus :  improvementListData == null,
        child: ListView.separated(
            itemCount:  improvementListData?.length??0,
            padding: const EdgeInsets.all(0),
            physics: BouncingScrollPhysics(),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return _toListItemWidget(improvementListData[index]);
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(
                height: 0.5,
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                padding: const EdgeInsets.only(left: 15,right: 15),
                child: Container(
                  color: Color(0xFF303546),
                ),
              );
            }),
      ),
    );
  }

  Widget _toListItemWidget(RecordsImprovementListBean bean) {
   String text = bean?.content??"";
    return Container(
      padding: const EdgeInsets.only(top: 15),
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: const EdgeInsets.only(bottom: 6),
              child: Row(
                children: [
                  Container(
                    margin: const EdgeInsets.symmetric(horizontal: 5),
                    width: 5,
                    height: 5,
                    decoration: BoxDecoration(
                        color:bean?.status=="01"? Colors.transparent : ThemeRepository.getInstance().getMinorRedColor_F95355(),
                      borderRadius: BorderRadius.circular(32),
                  ),),
                  Container(child: Text("${bean?.nick??""}",style: TextStyle(color: Color(0XFF188EFB),fontSize: 14),),
                  ),
                  _toPhoneWidget(bean),
                  Spacer(),
                  Container(
                      padding: const EdgeInsets.only(right: 15,left: 8),
                      child: Text("${VgDateTimeUtils.getFormatTimeStr(bean?.createdate)}",style: TextStyle(color: Color(0XFF808388),fontSize: 11,height: 1.6))),
                ],
              ),
            ),
            Visibility(
              visible: (text?.length??0)!=0,
              child: Container(
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 15,right: 15,bottom: 10),
                child: TextLimitDisplay(text:text,minLines: 3,textStyle:TextStyle(
                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 14),keyColor:ThemeRepository.getInstance().getPrimaryColor_1890FF(),shrinkText:'展开',expandText:'收起',onExpand:(){
                  bean?.showText = !(bean?.showText??false); setState(() {});
                },onShrink: (){bean?.showText = !(bean?.showText??false); setState(() {});
                },isExpandText: bean?.showText,),
              ),
            ),
            Visibility(
              visible: StringUtils.isNotEmpty(bean?.picurl) ,
              child: Container(
                padding: const EdgeInsets.only(bottom: 15,left: 15),
                alignment: Alignment.centerLeft,
                child: _toTitleWidget(bean),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///图片展示栏
  Widget _toTitleWidget(RecordsImprovementListBean bean) {
    // List<String> listUrl = List<String>();
    // List<UploadMediaLibraryItemBean> _uploadList = List();
    //错误数据处理
    if(bean?.picurl!=null && bean?.picurl!="" && bean?.picurl !="()"){
      String picurl = bean?.picurl?.replaceAll("(", "");
      picurl = picurl?.replaceAll(")", "");
      bean?.listUrl =  picurl?.split(",");
      bean?.listUrl?.forEach((element) {
        chuLPicture(element,bean?.uploadList);
      });
    }
    if(MatisseUtil.isVideo(bean?.video)){
      List<String> listVideoUrl = List<String>();
      listVideoUrl = bean?.video?.split(",");
      listVideoUrl?.forEach((element) {
        bean?.listUrl?.add(element);
        handleVideo(element,bean?.uploadList);
      });
    }
    double _itemWidth = (ScreenUtils.screenW(context) - 15 - 15 - 6)/3;
    int count = bean?.listUrl?.length??0;
    if(count > 3){
      count = 3;
    }
    return Container(
        height: _itemWidth,
        child: GridView.builder(
            itemCount: count,
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.all(0),
            physics: NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 1,
                mainAxisSpacing: 3,
                childAspectRatio: 1
            ),
            itemBuilder: (BuildContext context, int index) {
              // print("gzz2::${bean?.listUrl?.elementAt(index)}");
              return _toListPhotoWidget(context, bean?.listUrl?.elementAt(index),bean?.listUrl,index,bean?.uploadList, _itemWidth);
            }));
  }

  void chuLPicture(String clipPath,List<UploadMediaLibraryItemBean> _uploadList) async{
    if (StringUtils.isNotEmpty(clipPath)) {
        _uploadList.add(UploadMediaLibraryItemBean(
            netUrl: clipPath,
            mediaType: MediaType.image,));
    }
  }

  ///处理视频的逻辑
  void handleVideo(String localUrl,List<UploadMediaLibraryItemBean> _uploadList) async{
    UploadMediaLibraryItemBean item = UploadMediaLibraryItemBean(
      localUrl: localUrl, mediaType: MediaType.video,);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }
    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    _uploadList?.add(item);
  }


  Widget _toListPhotoWidget(BuildContext context, String url,List<String> listUrl,int index,List<UploadMediaLibraryItemBean> _uploadList, double itemWidth){
    // int isUrl = 0;
    // if(MatisseUtil.isVideo(url)){
    //   for(int i = 0;i<_uploadList?.length;i++){
    //     if(url?.contains("/")&&url?.contains(".")){
    //       if(_uploadList[i]?.getLocalPicUrl()?.contains(url?.substring(url?.lastIndexOf("/",url?.lastIndexOf("/")),url?.lastIndexOf(".",url?.lastIndexOf("."))))){
    //         isUrl = i;
    //         print("gzz13::${i}");
    //       }
    //     }
    //   }
    // }
    // print("gzz11::${MatisseUtil.isVideo(url) &&_uploadList?.length!=0}：：${ MatisseUtil.isVideo(url) &&_uploadList?.length!=0  ? _uploadList[isUrl]?.getLocalPicUrl() : "123"}");
    return GestureDetector(
      onTap: () async {
        VgPhotoPreview.listForPage(
          context,
          _uploadList,
          initUrl: url,
          urlTrasformFunc: (item) => item?.getLocalPicUrl(),
          loadingTransformFunc: (item) => VgPhotoPreview.getImageQualityStr(
              item?.getLocalPicUrl(), ImageQualityType.middleDown),
        );
        // setState(() { });
      },
      child: Stack(
        fit: StackFit.expand,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: VgCacheNetWorkImage(
              // _uploadList[index]?.netUrl,
              MatisseUtil.isVideo(url) &&_uploadList?.length!=0  ? _uploadList[index]?.getLocalPicUrl()??null : url,
              imageQualityType: ImageQualityType.middleUp,
              width: itemWidth,
              height: itemWidth,
              // defaultErrorType: ImageErrorType.head,
              // defaultPlaceType: ImagePlaceType.head,
            ),
          ),
          if((listUrl?.length??0)>3&& index ==2)
          Positioned(
            top: 5,
            right: 5,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(11),
              child: Container(
                height: 18,
                width: 32,
                alignment: Alignment.center,
                color: ThemeRepository.getInstance().getBgOrSplitColor_191E31().withOpacity(0.7),
                child: Text("${listUrl?.length??0}图",style: TextStyle(fontSize: 10,color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),height: 1.1),),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  Widget _toPhoneWidget(RecordsImprovementListBean bean) {
    return Offstage(
      // offstage: false,
      offstage: bean?.phone == null || bean?.phone?.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(bean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }
}




